﻿using System.ComponentModel;
using WCFIServices;

namespace WCFServerService
{
	public class WcfServerPushServerBO
	{
		#region Members

		private static WcfServerPushServerBO instance = null;

		string message = "Empty String";
	    private Employee _employee;
	    static ClientQueueManagerBO clientQueueManagerBO = null;
		static ServerPushMessageBO serverPushMessageBO = null;

		#endregion

		#region Constructor

		private WcfServerPushServerBO()
		{
			if (clientQueueManagerBO == null)
				clientQueueManagerBO = new ClientQueueManagerBO();

			if (serverPushMessageBO == null)
				serverPushMessageBO = new ServerPushMessageBO();

			clientQueueManagerBO.PropertyChanged += PropertyChangedEvent; 
		}

		public static WcfServerPushServerBO Instance
		{
			get 
			{
				if (instance == null)
				{
					instance = new WcfServerPushServerBO();
				}
				return instance;
			}
		}

		public void RegisterClient(ClientInfo clientInfo)
		{
			clientQueueManagerBO.AddToQueue(clientInfo.GroupName, clientInfo.ClientName, clientInfo.PushMessageBoxAddress);
		}

		public string Message
		{
			get
			{
				return message;
			}
			set
			{
				message = value;
				clientQueueManagerBO.SetQueuePending();
			}
		}

	    public Employee Employee
	    {
	        get { return _employee; }
	        set
	        {
	            _employee = value;
                clientQueueManagerBO.SetQueuePending();
	        }
	    }

	    #endregion

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;

		public void PropertyChangedEvent(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "QueueItem.QueueState.Pending")
			{
				QueueItem queueItem = (QueueItem)sender;

				queueItem.QueueState = QueueItem.EQueueState.eQueueStateSending;

                if (!string.IsNullOrEmpty(Message) && Message != "Empty String")
			        serverPushMessageBO.SendPushMessage(Message, queueItem.PushMessageBoxAddress);
			    else
                    serverPushMessageBO.SendPushMessage(Employee, queueItem.PushMessageBoxAddress);

				queueItem.QueueState = QueueItem.EQueueState.eQueueStateIdle;
			}

			PropertyChangedEventHandler handler = this.PropertyChanged;
			if (handler != null)
				handler(sender, new PropertyChangedEventArgs(e.PropertyName));
		}

		#endregion

	}
}
